﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YArchitech.LIB;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class AirTerminalDimension : HYExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public override Result HYExecute(ref string TranName)
		{
			TranName = "标示";
			List<ViewType> viewTypes = YJKRevitTools.ListViewNeed(2);
			if (!YJKRevitTools.ViewCheck(base.UiDoc, viewTypes))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			if (AirTerminalDimension.hWndRevit == null)
			{
				AirTerminalDimension.hWndRevit = new YJKWindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			FrmDimension frmDimension = new FrmDimension(true);
			frmDimension.Show(AirTerminalDimension.hWndRevit);
			int wMsg = 7;
			AirTerminalDimension.SendMessage(AirTerminalDimension.hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			DimensionOperation dimensionOperation = new DimensionOperation(base.UiDoc, false, frmDimension);
			Result result;
			try
			{
				for (;;)
				{
					dimensionOperation.Execute();
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				frmDimension.Close();
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				frmDimension.Close();
				if (ex.Message.ToString() == "外部组件发生异常。")
				{
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
				else
				{
					MessageBox.Show(ex.Message, "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
					result = Autodesk.Revit.UI.Result.Failed;
				}
			}
			return result;
		}

		public static YJKWindowHandle hWndRevit;
	}
}
